package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

import static com.sky.constant.MessageConstant.UNKNOWN_ERROR;
import static com.sky.constant.MessageConstant.USERNAME_EXIST;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
//@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获sql异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //1.获取异常信息
        String message = ex.getMessage();
        //2.判断异常信息是否是用户名重复
        if(message.contains("Duplicate entry")){
            //2.1如果是用户名重复，截取重复的用户名，返回给前端错误信息
            String[] split = message.split(" ");
            String username = split[2];
            return Result.error(username + USERNAME_EXIST);
        }
        //2.2如果不是，返回未知错误
        return Result.error(UNKNOWN_ERROR);
    }

}
